﻿using System;
using Microsoft.SPOT;
using System.Threading;
using System.IO.Ports;
using System.Text;
using System.Collections;

namespace PandaDataLogger
{
  class SerialComm
  {
    bool isStarted;
    bool isDisposed;
    SerialPort sPort;
    int delimChar = 10; //LF = \n = 0A = 10 dec
    ManualResetEvent mre;

    public SerialComm()
    {
      mre = new ManualResetEvent(false);
    }

    public void Open()
    {
      if (isStarted || isDisposed) return;
      isStarted = true;
      sPort = new SerialPort("COM1", 115200);
      sPort.Open();

      new Thread(ReadLoop).Start();
    }

    public void Close()
    {
      isDisposed = true;
    }

    public void Wait()
    {
      mre.WaitOne();
    }

    private void ReadLoop()
    {
      while (!isDisposed)
      {
        string line = ReadString(delimChar);
        line = line.Trim().ToLower();
        MessageEventHandler.onMessageEvent(line);
        // Send reply back.
        //byte[] ba = Encode(line);
        //sPort.Write(ba, 0, ba.Length);
      }
      //Debug.Print("TTY Host Exited");
      mre.Set();
    }

    private string ReadString(int delim)
    {
      ArrayList al = new ArrayList();
      byte[] readBuf = new byte[1];
      int received = 0;
      while (true)
      {
        int toRead = readBuf.Length - received;
        int read = sPort.Read(readBuf, 0, 1);
				Debug.Print(readBuf[0].ToString());
        if (read == 0)
          break;
        al.Add(readBuf[0]);
        if (readBuf[0] == delim)
          break;
      }

      //byte[] bytes = al.ToArray(typeof(byte)) as byte[];
      //char[] chars = Encoding.UTF8.GetChars(bytes);
      //return new string(chars);
      return Decode(al.ToArray(typeof(byte)) as byte[]);
    }

    public void Send(string msg)
    {
      byte[] bmsg = Encode(msg);
      sPort.Write(bmsg, 0, bmsg.Length);
    }

    private byte[] Encode(string msg)
    {
      return Encoding.UTF8.GetBytes(msg);
    }

    private string Decode(byte[] bmsg)
    {
      char[] chars = Encoding.UTF8.GetChars(bmsg);
      return new string(chars);
    }
  }
}
